package one.bugu.android.demon.ui.activity.wallet;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.juefeng.android.framework.LKUtil;
import com.juefeng.android.framework.common.util.ToastUtils;
import com.juefeng.android.framework.view.annotation.LKContentView;
import com.juefeng.android.framework.view.annotation.LKInjectView;

import one.bugu.android.demon.R;

import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import one.bugu.android.demon.bean.BGTInfoBean;
import one.bugu.android.demon.bean.WalletInfoBean;
import one.bugu.android.demon.bean.snatch.WalletBean;
import one.bugu.android.demon.common.BaseHttpAsycResponceHandler;
import one.bugu.android.demon.common.MyBaseActivity;
import one.bugu.android.demon.constant.Constant;
import one.bugu.android.demon.constant.HttpConstant;
import one.bugu.android.demon.ui.activity.WarnMainActivity;
import one.bugu.android.demon.ui.activity.WebActivity;
import one.bugu.android.demon.ui.adapter.BGTInfoAdapter;
import one.bugu.android.demon.ui.refresh.SmartRefreshLayout;
import one.bugu.android.demon.ui.refresh.listener.OnRefreshLoadmoreListener;
import one.bugu.android.demon.ui.refresh.listener.RefreshLayout;
import one.bugu.android.demon.ui.widget.BaseTopBarView;
import one.bugu.android.demon.util.CodeUtils;
import one.bugu.android.demon.util.IntentUtils;
import one.bugu.android.demon.util.ParamUtils;
import one.bugu.android.demon.util.PreferencesUtil;
import one.bugu.android.demon.util.StatusBarUtils;

/**
 * bgt明细界面
 */
@LKContentView(R.layout.activity_bgtinfo)
public class BGTActivity extends MyBaseActivity {
    /**
     * topBar
     */
    @LKInjectView(R.id.btbv_btg_info)
    private BaseTopBarView baseTopBarView;
    /**
     * 显示总额title
     */
    @LKInjectView(R.id.tv_list_title)
    private TextView tv_list_title;
    /**
     * 显示列表title
     */
    @LKInjectView(R.id.tv_info_title)
    private TextView tv_info_title;

    /**
     * ETH兑换人民币总数
     */
    @LKInjectView(R.id.tv_eth_CNY)
    private TextView tv_eth_CNY;

    /**
     * 显示bgt明细的列表
     */
    @LKInjectView(R.id.bgt_listview)
    private ListView listView;

    /**
     * 显示bgt数量
     */
    @LKInjectView(R.id.bgt_num)
    private TextView bgtNum;

    /**
     * 兑换服务按钮
     */
    @LKInjectView(R.id.btn_exchange)
    private Button exchangeBtn;

    /**
     * 转账按钮
     */
    @LKInjectView(R.id.btn_transferaccounts)
    private Button transferaccountsBtn;

    /**
     * 刷新控件
     */
    @LKInjectView(R.id.ref_layout)
    private SmartRefreshLayout ref_layout;

    private BGTInfoAdapter bgtInfoAdapter;

    /**
     * 兑换跳转请求码
     */
    private final int EXCHANGE_KEY = 100;

    private int limit = 30;

    private int offset = 1;

    String token;
    private String title;

    private DecimalFormat ethFormat = new DecimalFormat("###.##");
    private DecimalFormat df = new DecimalFormat("###.#####");
    private WalletBean walletData;

    @SuppressLint("SetTextI18n")
    @Override
    public void initView() {
        super.initView();
        //设置状态栏显示
        StatusBarUtils.getInstance().setStatusBar(this, baseTopBarView);

        bgtInfoAdapter = new BGTInfoAdapter(this);
        listView.setAdapter(bgtInfoAdapter);

        ref_layout.setEnableRefresh(true);//启用刷新
        ref_layout.setEnableLoadmore(true);//启用加载
    }


    /**
     * 获取bgt信息的方法
     */
    @SuppressLint("SetTextI18n")
    @Override
    protected void initData() {
        super.initData();
        Intent intent = getIntent();
        walletData = (WalletBean) intent.getSerializableExtra(Constant.NUMBER);
        bgtNum.setText(df.format(walletData.getBalance()));
        tv_eth_CNY.setText("≈¥" + ethFormat.format(walletData.getBalance() * walletData.getPrice()));
        title = intent.getStringExtra(Constant.PAGETITLE);
        title = title == null ? "我的BGT" : title;

        //配置页面信息
        setPageInfo();
        token = PreferencesUtil.getInstance().getString(BGTActivity.this, Constant.TOKEN);
        getNetWorkData();
    }

    @Override
    protected void onResume() {
        super.onResume();
        //数据刷新标记 在二级页面数据改变后返回当前页面时进行数据刷新
        boolean draw_suc = PreferencesUtil.getInstance().getBoolean(this, "DRAW_SUC", false);
        if (draw_suc) {
            //改变标记状态
            PreferencesUtil.getInstance().putBoolean(this, "DRAW_SUC", false);
            offset = 1;
            getNetWorkData();
            //刷新币种数据
            getWalletData();

            //通知钱包首页进行数据刷新
            setResult(RESULT_OK);
        }
    }

    /**
     * 请求数据接口
     */
    private void getBgtDetails(String type) {
        Map<String, String> map = new HashMap<>();
        map.put("token", token);
        map.put("wallteTypeId", type);
        map.put("limit", String.valueOf(limit));
        map.put("offset", String.valueOf(offset));
        map.put("sort", "createTime");
        map.put("order", "desc");
        LKUtil.getHttpManager().postBody(HttpConstant.GETUSERWALLET_URL, map, handler);
    }

    /**
     * 获取bgt信息的网络请求
     */
    @SuppressLint("HandlerLeak")
    public BaseHttpAsycResponceHandler<WalletInfoBean> handler = new BaseHttpAsycResponceHandler<WalletInfoBean>(true) {
        @Override
        public void onSuccess(WalletInfoBean data) {
            super.onSuccess(data);
            List<BGTInfoBean> bgtInfoBeans = data.getFolwList();
            ref_layout.finishRefresh();
            ref_layout.finishLoadmore();
            if (offset == 1) {
                bgtInfoAdapter.updateData(bgtInfoBeans);
            } else {
                bgtInfoAdapter.addData(bgtInfoBeans);
            }
            if (bgtInfoBeans == null || bgtInfoBeans.size() < limit) {
                ref_layout.setEnableLoadmore(false);
            } else {
                ref_layout.setEnableLoadmore(true);
            }
        }

        @Override
        public void onFailed(int code, String message) {
            super.onFailed(code, message);
            ref_layout.finishRefresh();
            ref_layout.finishLoadmore();
            if (offset > 1) offset--;
        }

        @Override
        public void onError() {
            super.onError();
            ref_layout.finishRefresh();
            ref_layout.finishLoadmore();
            if (offset > 1) offset--;
        }
    };

    /**
     * 获取钱包数据, 用于bgt兑换/eth提现时更新数据使用
     */
    private void getWalletData() {
        Map<String, Object> map = new HashMap<>();
        map.put("token", token);
        LKUtil.getHttpManager().postBody(HttpConstant.GET_USER_WALLET, map, getSnatchPeriodHander);
    }

    @SuppressLint("HandlerLeak")
    private BaseHttpAsycResponceHandler getSnatchPeriodHander =
            new BaseHttpAsycResponceHandler<List<WalletBean>>() {
                @SuppressLint("SetTextI18n")
                @Override
                public void onSuccess(List<WalletBean> walletBeans) {
                    super.onSuccess(walletBeans);
                    assert walletBeans != null;
                    for (int i = 0; i < walletBeans.size(); i++) {
                        WalletBean walletBean = walletBeans.get(i);
                        assert walletBean != null;
                        if (TextUtils.equals("我的BGT", title)) {
                            //bgt兑换刷新数据
                            if (walletBean.getWallteType() == 30) {
                                bgtNum.setText(new DecimalFormat("###.#####").format(walletBean.getBalance()) + "");
                            }
                        } else if (TextUtils.equals("我的ETH", title)) {
                            //eth提现后刷新数据
                            if (walletBean.getWallteType() == 50) {
                                tv_eth_CNY.setText("≈¥" + ethFormat.format(walletData.getPrice() * walletBean.getBalance()));
                                bgtNum.setText(new DecimalFormat("###.#####").format(walletBean.getBalance()) + "");
                            }
                        }
                    }
                }

                @Override
                public void onFailed(int code, String message) {
                    super.onFailed(code, message);

                }

                @Override
                public void onError() {
                    super.onError();

                }
            };

    @Override
    protected void initEvent() {
        super.initEvent();
        //topBar事件处理
        baseTopBarView.setEventInterface(new BaseTopBarView.EventInterface() {
            @Override
            public void leftOnClick() {
                finish();
            }

            @Override
            public void leftCloseClick() {

            }

            @Override
            public void rightOnClick() {
                if (TextUtils.equals("我的BGT", title)) {
                    Intent intent = new Intent(BGTActivity.this, WarnMainActivity.class);
                    intent.putExtra(Constant.ID, 1);
                    startActivity(intent);
                    finish();
                } else {
                    //充值查询
                    String weChatAccount = PreferencesUtil.getInstance().getString(BGTActivity.this, Constant.WECHAT_ACCOUNT);
                    String accountU8 = CodeUtils.getInstance().str2Utf8(weChatAccount);
                    List<ParamUtils.NameValue> parList = ParamUtils.build().put(WebActivity.TITLE, "充值查询").put(WebActivity.URL, HttpConstant.RECHARGE_QUERY_H5_URL + "?wechatAccount=" + accountU8).create();
                    IntentUtils.startAty(BGTActivity.this, WebActivity.class, parList);
                }

            }
        });
        //刷新加载
        ref_layout.setOnRefreshLoadmoreListener(new OnRefreshLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                offset++;
                getNetWorkData();
            }

            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                //刷新数据
                ref_layout.setEnableLoadmore(true);
                offset = 1;
                getNetWorkData();
                if (!TextUtils.equals("我的BGT", title)) {
                    //ETH充值刷新
                    //刷新币种数据
                    getWalletData();
                    setResult(RESULT_OK);
                }
            }
        });

        //兑换/充值服务
        exchangeBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (TextUtils.equals("我的BGT", title)) {
                    //提现
                    ToastUtils.custom("敬请期待");
                } else {
                    //充值
                    String weChatAccount = PreferencesUtil.getInstance().getString(BGTActivity.this, Constant.WECHAT_ACCOUNT);
                    String accountU8 = CodeUtils.getInstance().str2Utf8(weChatAccount);
                    List<ParamUtils.NameValue> parList = ParamUtils.build().put(WebActivity.TITLE, "ETH充值").put(WebActivity.URL, HttpConstant.RECHARGE_H5_URL + "?wechatAccount=" + accountU8).create();
                    IntentUtils.startAty(BGTActivity.this, WebActivity.class, parList);
                }
            }
        });

        //转账
        transferaccountsBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (TextUtils.equals("我的BGT", title)) {
                    ToastUtils.custom("敬请期待");
                } else {
                    String ethCNY = bgtNum.getText().toString().trim();
                    List<ParamUtils.NameValue> values = ParamUtils.build().put(WithDrawActvity.ETH_DATA, ethCNY).create();
                    IntentUtils.startAty(BGTActivity.this, WithDrawActvity.class, values);
                }
            }
        });
        //条目点击
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                List<BGTInfoBean> allData = bgtInfoAdapter.getAllData();
                if (allData != null) {
                    BGTInfoBean bgtInfoBean = allData.get(position);
                    assert bgtInfoBean != null;
                    Intent intent = new Intent(BGTActivity.this, WalletDetailsActivity.class);
                    intent.putExtra(WalletDetailsActivity.WALLET_DATA, bgtInfoBean);
                    startActivity(intent);
                }

            }
        });

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && requestCode == EXCHANGE_KEY) {
            //兑换过商品,页面重新刷新数据
            offset = 1;
            getNetWorkData();
        }
    }

    /**
     * 根据title配置页面信息
     */
    private void setPageInfo() {
        tv_info_title.setText(TextUtils.equals("我的BGT", title) ? "BGT总额" : "ETH总额");
        tv_list_title.setText(TextUtils.equals("我的BGT", title) ? "BGT明细" : "ETH明细");
        baseTopBarView.setRightTVContent(TextUtils.equals("我的BGT", title) ? "获取BGT" : "充值查询");
        tv_eth_CNY.setVisibility(TextUtils.equals("我的BGT", title) ? View.GONE : View.VISIBLE);
        exchangeBtn.setText(TextUtils.equals("我的BGT", title) ? "提现" : "充值");
        //设置title显示
        baseTopBarView.setTitle(title);
    }

    /**
     * 网络数据请求
     */
    private void getNetWorkData() {
        if (TextUtils.equals("我的BGT", title)) {
            //请求BGT数据
            getBgtDetails("30");
        } else {
            //请求ETH数据
            getBgtDetails("50");
        }
    }
}


